﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psl.Chat;

namespace Stl.Chat.Remoting.Plugin
{
    public class NeutralProxy : MarshalByRefObject, IDisposable, IChat
    {
        protected IChat remote = null;

        public NeutralProxy(IChat remote)
        {
            LinkTo(remote);
        }

        #region IDisposable Members

        public void Dispose()
        {
            LinkTo(null);
        }

        #endregion

        // gestion du chaînage et l'abonnement à l'événement Changed
        protected virtual void LinkTo(IChat what)
        {
            if (remote != null) remote.ChatChanged -= OnChatChanged;
            remote = what;
            if (remote != null) remote.ChatChanged += OnChatChanged;
        }

        public virtual void OnChatChanged(object sender, ChatChangedEventArgs e)
        {
            FireChatChanged(sender, e);
        }

        public virtual void FireChatChanged(object sender, ChatChangedEventArgs e)
        {
            if (ChatChanged != null)
                ChatChanged((sender == remote ? this : sender), e);
        }

        #region IChat Members

        public virtual void Add(string userID, string message)
        {
            remote.Add(userID, message);
        }

        public event ChatChangedEventHandler ChatChanged;

        public virtual int Chrono
        {
            get { return remote.Chrono; }
        }

        public virtual void Clear()
        {
            remote.Clear();
        }

        public virtual int Count
        {
            get { return remote.Count; }
        }

        public virtual ChatItem[] GetLasts(int from)
        {
            return remote.GetLasts(from);
        }

        public virtual string GetNewUserID()
        {
            return remote.GetNewUserID();
        }

        public virtual ChatItem[] History
        {
            get { return remote.History; }
        }

        public virtual ChatItem this[int index]
        {
            get { return remote[index]; }
        }

        #endregion

    }
}
